package com.example.xmlfactory.parse;

import com.example.xmlfactory.util.XMLUtil;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by huangbei on 2017/9/11.
 */

public class ClassMsg {
    private Class cl;
    private String className;
    private Map<String , Var> properties;

    private Object obj;

    public ClassMsg(Class cl){
        this.cl = cl;
        this.obj = null;
        initClass();
    }

    public ClassMsg(Object obj){
        this.cl = obj.getClass();
        this.obj = obj;
        initClass();
    }

    private void initClass(){
        properties = new HashMap<>();

        this.className = cl.getSimpleName();
        Field[] fs = cl.getDeclaredFields();
        for ( int i = 0 ; i < fs. length ; i++) {
            Field f = fs[i];
            f.setAccessible(true); // 设置些属性是可以访问的
            String type = f.getType().toString(); //得到此属性的类型
            String name = f.getName(); //得到此属性的名称
            if(XMLUtil.propertyfilter(name)) {
                Var var = new Var();
                var.setName(name);
                var.setType(type);
                try {
                    if (obj != null) {
                        var.setValue(f.get(obj));
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
                properties.put(name, var);
            }
        }
    }

    public void addValue(String name,String value){
        Var var = properties.get(name);
        if(var != null){
            var.setValue(value);
        }
    }

    //生成一个对象
    public Object generateObj(){
        try {
            Object obj = Class.forName(cl.getName()).newInstance();
            Field[] fs = cl.getDeclaredFields();
            for( int i=0;i<fs.length;i++){
                Field f = fs[i];
                f.setAccessible(true);
                String name = f.getName();
                if(XMLUtil.propertyfilter(name)) {
                    Var var = properties.get(name);
                    f.set(obj, var.getValue());
                }
            }
            clearProperty();
            return obj;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    //将参数的值都清除掉
    public void clearProperty(){
        Set<String> keySet = properties.keySet();
        for(String key : keySet){
            Var var = properties.get(key);
            if(var!=null){
                var.clearValue();
            }
        }
    }

    public String getClassName() {
        return className;
    }

    public Map<String, Var> getProperties() {
        return properties;
    }

    public boolean isProperty(String name){
        return properties.get(name)==null?false:true;
    }
}
